﻿using DevelopTool.Bll.ChatBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Model.ChatModels;
using Sunny.UI;
using System;
using System.Net;
using System.Windows.Forms;

namespace DevelopTool.Forms.ChatForms
{
    /// <summary>
    /// 手动添加用户
    /// </summary>
    public partial class SearchAndAddUserForm : BaseUIForm
    {
        /// <summary>
        /// 搜索到的用户
        /// </summary>
        public ChatUser ChatUser { get; set; }

        /// <summary>
        /// 是否显示搜索容器
        /// </summary>
        public bool IsShowSearchGrp { get; set; } = true;

        /// <summary>
        /// 是否显示用户信息容器
        /// </summary>
        public bool IsShowUserInfoGrp { get; set; } = false;

        /// <summary>
        /// 是否显示备注容器
        /// </summary>
        public bool IsShowRemarkNamePnl { get; set; } = false;

        /// <summary>
        /// 是否显示确认按钮
        /// </summary>
        public bool IsShowBtnOkGrp { get; set; } = false;

        /// <summary>
        /// 搜索的IP
        /// </summary>
        public string SearchUserIP { get; set; }


        private ChatBll chatBll;


        public SearchAndAddUserForm()
        {
            InitializeComponent();
            this.chatBll = new ChatBll();
        }

        private void SearchAndAddUserForm_Load(object sender, EventArgs e)
        {
            ChatBll.ChatUserChangedEvent += ChatBll_StaticChatUserChangedEvent;

            this.txtUserPort.Text = Setting.Chat.Port.ToString();//默认端口号

            ThemHelper.SetSystemThem(this);

            this.grpUserInfo.Visible = this.IsShowUserInfoGrp;

            this.grpSearch.Visible = this.IsShowSearchGrp;

            this.grpBtnOk.Visible = this.IsShowBtnOkGrp;

            this.pnlRemarkName.Visible = this.IsShowRemarkNamePnl;

            SearchUserIP = string.Empty;
        }


        private void ChatBll_StaticChatUserChangedEvent(ChatUser chatUser)
        {
            this.BeginInvoke(new Action(() =>
            {
                if (chatUser.IP == this.txtUserIP.Text && chatUser.Port == this.txtUserPort.IntValue)
                {
                    SetUserInfo(chatUser);

                    this.grpBtnOk.Visible = true;
                    this.pnlRemarkName.Visible = true;
                }
            }));
        }


        /// <summary>
        /// 设置用户信息
        /// </summary>
        /// <param name="chatUser"></param>
        public void SetUserInfo(ChatUser chatUser)
        {
            this.ChatUser = chatUser;

            string r = Environment.NewLine;
            //显示用户信息
            string userInfo = $"状态：{(chatUser.IsLine ? "在线" : "离线")}{r}昵称：{chatUser.NikeName}{r}计算机名称：{chatUser.ComputerName}{r}系统用户名称：{chatUser.SystemUserName}{r}系统版本：{chatUser.SystemOsName}{r}应用名称：{chatUser.AppName}";
            this.txtUserInfo.Text = userInfo;

            ChatUser user = this.chatBll.GetUserByUserId(this.ChatUser.UserId);
            if (user != null)
            {
                this.txtUserRemarkName.Text = user.RemarkName;
            }

            this.grpUserInfo.Visible = true;
        }


        /// <summary>
        /// 查找用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchUser_Click(object sender, EventArgs e)
        {
            if (!base.CheckData(this.txtUserIP, "请输入IP地址"))
            {
                this.txtUserIP.Focus();
                return;
            }

            if (!this.txtUserIP.Text.IsIPv4())
            {
                this.ShowErrorTip(this.txtUserIP, "请输入正确的IPV4地址");
                return;
            }

            if (!base.CheckData(this.txtUserPort, "请输入端口号"))
            {
                this.txtUserPort.Focus();
                return;
            }

            if (this.txtUserPort.IntValue <= 0)
            {
                this.ShowErrorTip(this.txtUserPort, "请输入端口号");
                return;
            }

            this.btnSearchUser.Enabled = false;
            this.grpUserInfo.Visible = false;
            this.grpBtnOk.Visible = false;

            //在后台给用户发送发现广播
            this.backgroundWorker_SearchUser.RunWorkerAsync(new Tuple<string, int>(this.txtUserIP.Text, this.txtUserPort.IntValue));
        }


        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (this.ChatUser == null) return;

            this.ChatUser.RemarkName = this.txtUserRemarkName.Text;
            this.ChatUser = this.chatBll.SetChatUserRemarkName(this.ChatUser.UserId, this.txtUserRemarkName.Text);

            this.DialogResult = DialogResult.OK;
        }


        /// <summary>
        /// 在后台给指定IP发送发现广播
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker_SearchUser_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument is Tuple<string, int> tuple)
            {
                try
                {
                    ChatNetworkBll.SendDiscoveryBroadcastMessage(IPAddress.Parse(tuple.Item1), tuple.Item2);

                    backgroundWorker_SearchUser.ReportProgress(1);//报告状态，展示结果 
                }
                catch (Exception ex)
                {
                    backgroundWorker_SearchUser.ReportProgress(0, ex.Message);//报告状态，展示结果  
                }
            }
        }


        private void backgroundWorker_SearchUser_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 0)//异常
            {
                this.ShowErrorNotifier(e.UserState.ToString());
            }
            else
            {
                this.ShowSuccessTip(this.btnSearchUser, "指令已发送，请等待用户回应~");
            }
        }


        private void backgroundWorker_SearchUser_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            this.btnSearchUser.Enabled = true;
        }


        private void SearchAndAddUserForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ChatBll.ChatUserChangedEvent -= ChatBll_StaticChatUserChangedEvent;

            this.backgroundWorker_SearchUser.CancelAsync();
            this.backgroundWorker_SearchUser.Dispose();
        }

    }
}
